import db from '@/db'
import { v4 as uuidv4 } from 'uuid'
import conversationService from '@/service/conversationService'
import userService from '@/service/userService'

/**
 * 用于操作folder表的service
 */
export default {

  /**
   * 添加文件夹
   */
  async addFolder(title) {
    // 先获取当前最大的order，默认为0，如果有值，那么就取最大的order
    const maxOrder = await db.folder.orderBy('order').last()
    const user = await userService.getCurrent()
    const folder = {
      id: uuidv4(),
      title,
      type: 'custom', // 'system' | 'custom
      order: maxOrder ? maxOrder.order + 1 : 0,
      createTime: new Date().getTime(),
      userId: user.id,
    }

    return db.folder.add(folder)
  },

  /**
   * 删除文件夹
   * @param id
   */
  async removeFolder(id) {
    if (!id && id === 1) {
      return Promise.reject(new Error('Can not remove default folder'))
    }

    // 删除文件夹下的所有对话
    return db.folder.delete(id).then(() => conversationService.moveFolderToDefault(id))
  },

  /**
   * 创建默认文件
   * @returns {Promise<*>}
   */
  async createDefaultFolder() {
    const folder = {
      id: 1,
      title: 'Unsorted',
      type: 'unsorted', // 'system' | 'custom
      order: 0,
      createTime: new Date().getTime(),
      userId: 0,
    }

    return db.folder.add(folder)
  },

  /**
   * 移动文件夹排序
   */
  async moveFolder(id, oldIndex, newIndex) {
    const user = await userService.getCurrent()

    // 获取所有文件夹
    const folders = await db.folder
      .where('userId').equals(user.id)
      .or('type').anyOf(['system'])
      .orderBy('order')
      .toArray()

    // 从数组中删除当前文件夹，并插入到新的位置
    // 因为删除了一个元素，所以newIndex要减1
    const currentFolder = folders.splice(oldIndex, 1)[0]
    folders.splice(newIndex, 0, currentFolder)

    folders.forEach((folder, index) => {
      db.folder.update(folder.id, {
        order: index + 1,
      })
    })
  },

}
